package com.zh.business.service.web.user.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.business.service.web.user.IDRoleService;
import com.zh.business.mapper.user.*;
import com.zh.business.service.web.user.IDUserService;
import com.zh.business.util.CommonUtils;
import com.zh.business.vo.web.AuthMenuVo;
import com.zh.zhbootcommon.entity.user.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author JueDream
 * @since 2021-08-04
 */
@Service
public class DUserServiceImpl extends ServiceImpl<DUserMapper, User> implements IDUserService {

    @Autowired
    IDRoleService roleService;

    @Autowired
    DUserMapper userMapper;

    @Autowired
    DRoleMapper roleMapper;

    @Autowired
    DPermissionMapper permissionMapper;

    @Autowired
    DLevelInfoMapper levelInfoMapper;

    @Autowired
    DRolePermissionRelationMapper rolePermissionRelationMapper;

    @Autowired
    DUserRoleRelationMapper userRoleRelationMapper;

    @Autowired
    DUserPermissionRelationMapper userPermissionRelationMapper;


    @Override
    public Page<User> queryUserPage(Integer page, Integer limit, String userName) {
        Page<User> userIPage = new Page<>(page, limit);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        if (StrUtil.isNotBlank(userName)) {
            queryWrapper.like(User::getUserName, userName);
        }
        queryWrapper.eq(User::getDelFlg, '0');
        userIPage = userMapper.selectPage(userIPage, queryWrapper);
        Optional.ofNullable(userIPage.getRecords()).orElse(new ArrayList<>())
                .forEach(u -> {
                    if (Objects.nonNull(u.getUserLevelId())) {
                        LevelInfo levelInfo = levelInfoMapper.selectById(u.getUserLevelId());
                        if (Objects.nonNull(levelInfo)) {
                            u.setUserLeveName(levelInfo.getLevelName());
                        }
                    }
                    List<Role> roleList = roleService.queryRoleList(u.getUserId());
                    u.setRoles(roleList);
                    if (u.getRoles().size() > 0) {
                        List<String> roleIds = u.getRoles().stream().map(r -> String.valueOf(r.getRoleId()))
                                .collect(Collectors.toList());
                        String roleIdStr = roleIds.stream().collect(Collectors.joining(","));
                        u.setRoleIds(roleIdStr);
                    }
                });

        userIPage.setTotal(userIPage.getRecords().size());
        return userIPage;
    }

    @Override
    public List<User> queryUserAll() {
        List<User> userList = new ArrayList<>();
        // 查询司机角色和用户的关系
        LambdaQueryWrapper<UserRoleRelation> queryURWrapper = new LambdaQueryWrapper<UserRoleRelation>();
        queryURWrapper.eq(UserRoleRelation::getRoleId, "2");
        List<UserRoleRelation> urList = userRoleRelationMapper.selectList(queryURWrapper);
        List<Integer> userIds = new ArrayList<>();
        if (urList.size() > 0) {
            userIds = urList.stream().map(r -> r.getUserId()).collect(Collectors.toList());
            LambdaQueryWrapper<User> queryUWrapper = new LambdaQueryWrapper<User>();
            queryUWrapper.in(User::getUserId, userIds);
            userList = userMapper.selectList(queryUWrapper);
        }
        return userList;
    }

    @Override
    public boolean removeUser(Integer userId) {
        boolean flag = false;
        User userInfo = userMapper.selectById(userId);
        if (Objects.nonNull(userInfo)) {
            userInfo.setDelFlg(1);
            Integer result = userMapper.updateById(userInfo);
            if (result > 0) {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public User findUserById(Integer userId) {
        User user = userMapper.selectById(userId);
        if (Objects.nonNull(user)) {
            user = bindUserInfo(user);
        }
        return user;
    }

    @Override
    public User queryUserInfo(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserAccount, user.getUserAccount());
        queryWrapper.eq(User::getDelFlg, "0");
        user = userMapper.selectOne(queryWrapper);
        if (Objects.nonNull(user)) {
            user = bindUserInfo(user);
        }
        return user;
    }

    @Override
    public User findUserByAccountPwd(String userName, String Password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserAccount, userName);
        queryWrapper.eq(User::getUserPassword, Password);
        queryWrapper.eq(User::getDelFlg, "0");
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.nonNull(user)) {
            user = bindUserInfo(user);
        }
        return user;
    }

    @Override
    public User registerUser(String registerUsername, String registerPassword, String selectValue) {
        // 验证账户是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserAccount, registerUsername);
        queryWrapper.eq(User::getDelFlg, "0");
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            // 新增用户
            user = User.builder().userName(registerUsername)
                    .userAccount(registerUsername)
                    .userPassword(registerPassword)
                    .userLevelId(1).userSex(2).build();
            userMapper.insert(user);
            // 新增用户角色关系 2-司机 3-乘客
            UserRoleRelation relation = UserRoleRelation.builder()
                    .roleId(Integer.parseInt(selectValue))
                    .userId(user.getUserId()).build();
            userRoleRelationMapper.insert(relation);
        }
        return user;
    }

    @Override
    public boolean bindAuthMenu(AuthMenuVo vo) {
        Integer result = 0;
        // 绑定用户角色权限;删除该用户对应的角色菜单
        LambdaQueryWrapper<UserRoleRelation> queryURWrapper = new LambdaQueryWrapper();
        queryURWrapper.eq(UserRoleRelation::getUserId, vo.getUserId());
        result = userRoleRelationMapper.delete(queryURWrapper);
        LambdaQueryWrapper<UserPermissionRelation> queryUPWrapper = new LambdaQueryWrapper();
        queryUPWrapper.eq(UserPermissionRelation::getUserId, vo.getUserId());
        result = userPermissionRelationMapper.delete(queryUPWrapper);
        // 新增用户角色权限关系
        List<UserRoleRelation> roleRelations = new ArrayList<>();
        List<Integer> roleIds = vo.getRoleIds();
        for (int i = 0; i < roleIds.size(); i++) {
            roleRelations.add(UserRoleRelation.builder()
                    .userId(vo.getUserId())
                    .roleId(roleIds.get(i))
                    .build());
        }
        result = userRoleRelationMapper.insertBatchSomeColumn(roleRelations);
        List<UserPermissionRelation> userPermissionRelations = new ArrayList<>();
        List<Integer> pIds = vo.getPIds();
        for (int i = 0; i < pIds.size(); i++) {
            userPermissionRelations.add(UserPermissionRelation.builder()
                    .userId(vo.getUserId())
                    .pId(pIds.get(i))
                    .build());
        }
        result = userPermissionRelationMapper.insertBatchSomeColumn(userPermissionRelations);
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 绑定用户权限菜单
     *
     * @param user
     * @return
     */
    private User bindUserInfo(User user) {
        // 查询用户角色
        LambdaQueryWrapper<UserRoleRelation> queryURWrapper = new LambdaQueryWrapper();
        queryURWrapper.eq(UserRoleRelation::getUserId, user.getUserId());
        List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectList(queryURWrapper);

        List<Integer> roleIds = userRoleRelations.stream().map(rp -> rp.getRoleId()).collect(Collectors.toList());
        LambdaQueryWrapper<Role> queryRWrapper = new LambdaQueryWrapper();
        queryRWrapper.in(Role::getRoleId, roleIds);
        List<Role> roles = roleMapper.selectList(queryRWrapper);
        user.setRoles(roles);
        // 查询用户权限
        LambdaQueryWrapper<RolePermissionRelation> queryRPWrapper = new LambdaQueryWrapper();
        queryRPWrapper.in(RolePermissionRelation::getRoleId, roleIds);
        List<RolePermissionRelation> rolePermissionRelations = rolePermissionRelationMapper.selectList(queryRPWrapper);

        List<Integer> permissIds = rolePermissionRelations.stream().map(rp -> rp.getPId()).collect(Collectors.toList());
        LambdaQueryWrapper<Permission> queryPWrapper = new LambdaQueryWrapper();
        queryPWrapper.in(Permission::getPId, permissIds);
        List<Permission> permisss = permissionMapper.selectList(queryPWrapper);
        // 递归查询权限菜单
        permisss = permisss.stream().distinct().collect(Collectors.toList());
        permisss = CommonUtils.mergeMenuList(permisss);
        user.setPermissions(permisss);
        return user;
    }
}
